from rest_framework.authentication import BaseAuthentication
from rest_framework_simplejwt.authentication import JWTAuthentication
from django.conf import settings
from django.contrib.auth.models import AnonymousUser

class SkipAuthForPaths(BaseAuthentication):
    """
    自定义认证类：跳过指定路径的认证
    """
    def authenticate(self, request):
        # 获取当前请求的路径
        path = request.path
        # 如果路径在 PASS_TOKEN 列表中
        if path in settings.PASS_TOKEN:
            try:
                # 使用 JWTAuthentication 解析 Token
                jwt_auth = JWTAuthentication()
                user, token = jwt_auth.authenticate(request)
            except Exception:
                # 如果 Token 无效，返回匿名用户
                return (AnonymousUser(), None)
            return (user, token)  # 返回认证用户和 Token
        # 否则，执行默认的认证逻辑
        return None